package com.guonl.config;

import com.guonl.model.ResponseResult;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Type;

public class RespDecoder implements Decoder {
    private final SpringDecoder springDecoder;

    public RespDecoder(SpringDecoder springDecoder) {
        this.springDecoder = springDecoder;
    }

    /**
     * feign解码器，如果ResponseResult code不为0，则抛出异常
     * @param response
     * @param type
     * @return
     * @throws IOException
     * @throws FeignException
     */
    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        Object decode = springDecoder.decode(response, type);

        if (decode instanceof ResponseResult) {
            ResponseResult<?> _decode = (ResponseResult<?>) decode;
            if (_decode.isSuccess()) {
                return _decode;
            }

            FeignException.FeignClientException feignClientException = new FeignException.FeignClientException(
                    response.status(),
                    _decode.getMsg(),
                    response.request(),
                    new byte[]{},
                    response.headers());

            //如果直接抛出这个异常，就可以使用spring-retry机制
            throw feignClientException;

            // 如果抛出RetryableException，可以使用feign自带的重试机制，默认的Retryer不开启重试，需要重新定义Retryer = new Retryer.Default();
//            throw new RetryableException(
//                    response.status(),
//                    feignClientException.getMessage(),
//                    response.request().httpMethod(),
//                    feignClientException,
//                    new Date(),
//                    response.request());
        }

        return decode;
    }
}
